//
//  UIImageView.m
//  crownbee
//
//  Created by sam on 16/5/25.
//  Copyright © 2016年 张小聪. All rights reserved.
//

#import "UIImageView+Circle.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDImageCache.h>
@implementation UIImageView(Circle)


- (void) sd_setCircleImageWithURL:(NSString *)surl placeholderImage:(UIImage *)placeholder
{
    if (surl==nil || surl.length==0) {
        self.image = placeholder;
        return;
    }
    NSURL *url=[NSURL URLWithString:surl];
    NSString *image_url_cache = [surl stringByAppendingString:@"cache_circle"];
    NSLog(@"image_url_cache   %@",image_url_cache);

    UIImage *cacheImage = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:image_url_cache];
    if (!cacheImage) {
        cacheImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:image_url_cache];
        self.image = cacheImage;
    }
    if (!cacheImage) {
        [self sd_setImageWithURL:url placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
        {
            if (!error)
            {
                UIImage *radiusImage = [self cicleImage:image withParam:1];
                self.image = radiusImage;
                [[SDImageCache sharedImageCache] storeImage:radiusImage forKey:image_url_cache completion:nil];
                [[SDImageCache sharedImageCache] removeImageForKey:surl withCompletion:nil];
            }
        }];
    }else{
        self.image = cacheImage;
    }
}

- (UIImage*) cicleImage:(UIImage*) image withParam:(CGFloat) inset {
    
    CGFloat max_h = 0;
    if (image.size.height>image.size.width) {
        max_h = image.size.width;
    }else{
        max_h = image.size.height;
    }
    if (inset==0) {
        inset = 1;
    }
    UIGraphicsBeginImageContext(CGSizeMake(max_h, max_h));
    
    CGContextRef context =UIGraphicsGetCurrentContext();
    //圆的边框宽度为2，颜色为红色
    
    CGContextSetLineWidth(context,2);
    
    CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
    
    //(image.size.width-max_h*inset)/2
    CGRect rect = CGRectMake(0, 0, max_h*inset, max_h*inset);
    
    CGContextAddEllipseInRect(context, rect);
    
    CGContextClip(context);
    
    //在圆区域内画出image原图
    
    [image drawInRect:rect];
    
    CGContextAddEllipseInRect(context, rect);
    
    CGContextStrokePath(context);
    
    //生成新的image
    
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return newimg;
}

@end
